(function () {
    'use strict';

    angular.module('KingAdmin.pages.pdev.device')
        .controller('DevmapCtrl', DevmapCtrl);

    /** @ngInject */
    function DevmapCtrl($scope, $filter, $window, toastr, DeviceService, CommonService) {
        var kt = this;
        kt.devicelist = [];

        kt.isShow = false;

        kt.gWindDirc = [
            '正北', '东北偏北', '东北', '东北偏东',
            '正东', '东南偏东', '东南', '东南偏南',
            '正南', '西南偏南', '西南', '西南偏西',
            '正西', '西北偏西', '西北', '西北偏北'
        ];

        kt.gWindLevel = [
            {'level': '0', 'name': '无风', 'low': 0, 'up': 0.3},
            {'level': '1', 'name': '软风', 'low': 0.3, 'up': 1.6},
            {'level': '2', 'name': '轻风', 'low': 1.6, 'up': 3.4},
            {'level': '3', 'name': '微风', 'low': 3.4, 'up': 5.5},
            {'level': '4', 'name': '和风', 'low': 5.5, 'up': 8.0},
            {'level': '5', 'name': '轻劲风', 'low': 8.0, 'up': 10.8},
            {'level': '6', 'name': '强风', 'low': 10.8, 'up': 13.9},
            {'level': '7', 'name': '疾风', 'low': 13.9, 'up': 17.2},
            {'level': '8', 'name': '大风', 'low': 17.2, 'up': 20.8},
            {'level': '9', 'name': '烈风', 'low': 20.8, 'up': 24.5},
            {'level': '10', 'name': '狂风', 'low': 24.5, 'up': 28.5},
            {'level': '11', 'name': '暴风', 'low': 28.5, 'up': 32.7},
            {'level': '12', 'name': '飓风', 'low': 32.7, 'up': 37.0},
            {'level': '13', 'name': '飓风', 'low': 37.0, 'up': 41.5},
            {'level': '14', 'name': '飓风', 'low': 41.5, 'up': 46.2}
        ];

        kt.mapHeight = $window.innerHeight - 66;

        kt.showCharts = CommonService.showEvCharts;


        kt.initBap = function () {
            console.log('初始化地图');
            kt.map = new BMap.Map("bmap-con");
            kt.map.centerAndZoom(new BMap.Point(119.147, 32.862), 8);  // 初始化地图，设置中心点坐标和地图级别
            kt.map.addControl(new BMap.NavigationControl());
            kt.map.addControl(new BMap.ScaleControl());
            kt.map.addControl(new BMap.OverviewMapControl());
            kt.map.enableScrollWheelZoom(true);

            //去除路网
            kt.map.setMapStyle({
                styleJson:[
                    {
                        "featureType": "road",
                        "elementType": "all",
                        "stylers": {
                            "color": "#ffffff",
                            "visibility": "off"
                        }
                    }
                ]
            });

            // 删除覆盖点
            var allOverlays = kt.map.getOverlays();
            for (var i = 0; i < allOverlays.length; i++) {
                kt.map.removeOverlay(allOverlays[i]);
            }

            angular.forEach(kt.devicelist, function (dev) {
                var lng = dev.device.lng;
                var lat = dev.device.lat;
                var marker = null;

                if (lng && lat) {
                    // 添加新的覆盖点
                    marker = new BMap.Marker(new BMap.Point(lng, lat));
                    kt.map.addOverlay(marker);
                }

                var infoContent = '<div class="dev-item">' +
                    '<div class="dev-label">设备名称：<span class="dev-value">' +dev.device.name+'</span></div>' +
                    '<div class="dev-label">设备UID：<span class="dev-value">'+ dev.device.deviceUid+'</span></div>' +
                    '<div class="dev-label">设备地址：<span class="dev-value">'+dev.device.address+'</span></div>' +
                    '</div>';

                infoContent += '<div class="map-btns">';

                if (dev.camera) {
                    infoContent += '<button type="button" class="btn-img btn btn-info  btn-xs disabled">设备图片</button>';
                    infoContent += '<button type="button" class="btn-video btn btn-warning  btn-xs">实时视频</button>';
                } else {
                    infoContent += '<button type="button" class="btn-img btn-info  btn-xs  disabled">设备图片</button>';
                    infoContent += '<button type="button" class="btn-video btn btn-warning  btn-xs disabled">实时视频</button>';
                }

                infoContent += '<button type="button" class="btn-alert btn btn-info btn-xs disabled">报警记录</button>';
                infoContent += '</div>';


                if(dev.channels && dev.channels.length > 0) {
                    infoContent += '<table class="b-map-info-win">\n' + '<tbody>\n';

                    angular.forEach(dev.channels, function (item, key) {
                        if (key % 2 == 0) {
                            infoContent += '<tr>\n';
                        }
                        var value = item['val'] + '</span>' + item['unit'];
                        var sensorType = item['type'];

                        // 风向单独设置
                        if (sensorType == '18') {
                            var deg = (item['val'] + 11.25) % 360;
                            var degIndex = parseInt(deg / 22.5);

                            value = kt.gWindDirc[degIndex] + '</span>';
                        } else if (sensorType == '17') {
                            // 风速单独设置
                            var windSpeed = item['val'];
                            var windSpeedLevel = '';
                            var windName = '';

                            for (var i = 0; i < kt.gWindLevel.length; i++) {
                                var curSpeedLevel = kt.gWindLevel[i];
                                if (windSpeed >= curSpeedLevel['low'] && windSpeed < curSpeedLevel['up']) {
                                    windSpeedLevel = curSpeedLevel['level'];
                                    windName = curSpeedLevel['name'];
                                    break;
                                }
                            }

                            value = windSpeedLevel + ' 级(' + windName + ')</span>';
                        }

                        infoContent += '<td>' + item['name'] + '[' + item['number'] + ']</td>\n' +
                            '<td  class="chn-info" data-name="' + item['name'] + '" data-chnid="' + item['id'] + '"><span class="text-info">' + value + '</td>\n';

                        if (key % 2 == 1) {
                            infoContent += '</tr>\n';
                        }

                        // 如果是最后一个，且为单数添加<\tr>
                        if ((key + 1) == dev.channels.length && key % 2 == 0) {
                            infoContent += '</tr>\n';
                        }
                    });

                    infoContent += '</tbody>\n' + '</table>';
                    infoContent += "<div class='upd-time'>更新时间于: <span class='text-info'>"+ dev.channels[0]['updateTime'] +"</span></div>";
                }
                var infoWindow = new BMap.InfoWindow(infoContent);

                var onlineStatus = '离线';
                if (dev.device.isOnline == true) {
                    onlineStatus = '在线';
                }
                var title ='<a href="#"><h4 style="font-weight: 700;">' + dev.device.name +'-- <span>(' + onlineStatus + ')</span></h4></a>';
                // title = '<a onclick="" href="#" ><h3 style="font-weight: 700;">' + '测试设备' + '</h3></a>';

                infoWindow.setWidth(360);
                infoWindow.setTitle(title);

                infoWindow.addEventListener("open", function (type, target, point) {
                    // 绑定通道信息
                    angular.element('.btn-video').bind('click', function (event, data) {
                        // 显示摄像头信息
                        CommonService.showHkVideo(dev.camera.id);
                    });

                    angular.element('.chn-info').bind('click', function (event, data) {
                        var chnId = $(this).data('chnid');
                        kt.showCharts(chnId);
                    })
                });

                if (marker != null)  {
                    marker.addEventListener("click", function () {
                        this.openInfoWindow(infoWindow);
                    });
                }
            });
        };


        // 页面完成后加载 地图
        $scope.$watch('$viewContentLoaded', function() {
            // kt.initBap();

            DeviceService.getAuthList({}, function (data) {
                kt.devicelist = data.result;
                kt.initBap();
            });
        });


    }

})();
